package com.ds.config;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class VerificationCode {
    //验证码图片宽度
    private int width = 100;
    //验证码的高度
    private int height = 30;
    //验证码字体
    private String[] fontName = {"宋体","楷体","微软雅黑"};
    //验证码图片的背景颜色
    private Color bgColor = new Color(225,223,225);
    //验证码的原文本
    private String codes = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
    //验证码图片上的字符串
    private String test;
    private Random random = new Random();

    public String getTest() {
        return test;
    }

    /**
     * 获取一张验证码
     * @return
     */
    public BufferedImage getImage(){
        BufferedImage image = createImage();
        //获取画笔
        Graphics2D graphics2D = (Graphics2D) image.getGraphics();
        //保存绘制在图片上的字符串
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            String s = randomChar();
            stringBuffer.append(s);
            //设置画笔的颜色
            graphics2D.setColor(randomColor());
            //设置字体随机样式
            graphics2D.setFont(randomFont());
            float f = i * width * 1.0f / 4;
            graphics2D.drawString(s,f,height-8);
            this.test = stringBuffer.toString();
        }
        drawLine(image);
        return image;
    }

    /**
     * 绘制干扰线
     * @param image
     */
    private void drawLine(BufferedImage image) {
        Graphics2D graphics2D = (Graphics2D) image.getGraphics();
        int num = 5;
        for (int i = 0; i < num; i++) {
            int w1 = random.nextInt(width);
            int h1 = random.nextInt(height);
            int w2 = random.nextInt(width);
            int h2 = random.nextInt(height);
            graphics2D.setColor(randomColor());
            graphics2D.setStroke(new BasicStroke(1.5f));
            graphics2D.drawLine(w1,h1,w2,h2);
        }
    }
    //设置随机字体
    private Font randomFont() {
        String name = String.valueOf(random.nextInt(fontName.length));
        int style = random.nextInt(4);
        int size = 24 + random.nextInt(5);
        return new Font(name,style,size);
    }

    private Color randomColor() {
        int red = random.nextInt(150);
        int green = random.nextInt(150);
        int blue = random.nextInt(150);
        return new Color(red,green,blue);
    }

    private String randomChar() {
        return String.valueOf(codes.charAt(random.nextInt(codes.length())));
    }

    /**
     * 创建一张空白的图片对象
     * @return
     */
    private BufferedImage createImage() {
        //创建一个图片对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取一个2d的画笔
        Graphics2D graphics2D = (Graphics2D) image.getGraphics();
        //设置图片背景
        graphics2D.setColor(bgColor);
        //填充图片
        graphics2D.fillRect(0,0,width,height);
        return image;
    }
}
